package socket.chat;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.Set;

public class Receiver extends Thread{
	private Socket socket; //建立名字为socket的套接字
	private Set<Socket> cs;  //建立一个Set集合来储存socket数
	public Receiver(Socket socket, Set<Socket> cs) {   //构造方法给socket和sort赋初值
		this.socket = socket;
		this.cs = cs;
	}
	@Override
	public void run() {  
		try {
			ObjectInputStream in=new ObjectInputStream(socket.getInputStream());
			// 从socket获得信息
			while(true){
				Object message=in.readObject(); //读取信息到message上
				for(Socket sk:cs){  
					ObjectOutputStream out=new ObjectOutputStream(sk.getOutputStream());
					//从cs里获取信息到sk
					out.writeObject(message);
					//写出信息
					out.flush();
					//刷新
				}
			}
		} catch (IOException e) {
			System.out.println(socket.getInetAddress().getHostAddress()+"出去了");
			cs.remove(socket);
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}		
	}
}
